import numpy as np

def Cal_Z(Vf, Vr):
    """计算阻抗
    
    Args:
        Vf (np.ndarray): 前向电压
        Vr (np.ndarray): 反射电压
        
    Returns:
        complex: 平均阻抗值
    """
    # 基本参数设置
    Fs = 117.402e6 / 14  # 采样率 [Hz]
    Toffset = 1e-6       # 偏移时间 [s]
    R = 0.95            # 阈值比例
    Noffset = int(np.ceil(Toffset * Fs))
    
    try:
        # 1. 找到RF关闭时刻
        DiffPf = np.abs(np.diff(np.abs(Vf)))
        if len(DiffPf) == 0:
            print("警告：信号太短，无法计算阻抗")
            return 0
            
        Noff = np.argmax(DiffPf) + 1
        
        # 2. 计算稳态振幅
        if Noff < 4*Noffset:
            print("警告：RF关闭时刻太早，无法计算稳态振幅")
            return 0
            
        ssPtA = np.mean(np.abs(Vr)[Noff - 4*Noffset : Noff - Noffset])
        if np.isnan(ssPtA) or ssPtA == 0:
            print("警告：稳态振幅计算失败")
            return 0
            
        # 3. 计算阈值和衰减结束点
        ssPtA_threshold = ssPtA * R
        above_threshold = np.where(np.abs(Vr) > ssPtA_threshold)[0]
        if len(above_threshold) == 0:
            print("警告：找不到衰减结束点")
            return 0
            
        Ndecay = np.max(above_threshold)
        
        # 4. 计算阻抗
        start_idx = Noff + 2
        end_idx = Noff + 10
        
        if start_idx >= len(Vf) or end_idx >= len(Vf):
            print("警告：计算区间超出信号范围")
            return 0
            
        # 避免除以零
        Vf_segment = Vf[start_idx:end_idx]
        if np.any(np.abs(Vf_segment) < 1e-10):
            print("警告：前向电压信号太弱")
            return 0
            
        Z = -Vr[start_idx:end_idx] / Vf_segment
        mean_Z = np.mean(Z)
        
        # 检查结果
        if np.isnan(mean_Z) or np.isinf(mean_Z):
            print("警告：计算得到无效阻抗值")
            return 0
            
        return mean_Z
        
    except Exception as e:
        print(f"计算阻抗时出错：{str(e)}")
        return 0

if __name__ == '__main__':
    # 测试代码
    t = np.linspace(0, 1, 1000)
    Vf_test = np.exp(-5*t) * np.sin(2*np.pi*10*t)
    Vr_test = 0.5 * Vf_test
    
    Z = Cal_Z(Vf_test, Vr_test)
    print(f"测试阻抗值：{Z:.2f}")